// src/components/DashboardChart.vue

<template>
  <div class="pie-chart-container">
    <div ref="pieChart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { sseManager } from '@/api/tool/sse-manager.js';

export default {
  name: "SalesPieChart",
  data() {
    return {
      chartInstance: null,
      debug: true, // 调试开关
      unsubscribe: null,
      option: {
        title: {
          text: '销售额分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '销售额',
            type: 'pie',
            radius: '55%',
            data: [
              { value: 650, name: '日销售额' },
              { value: 17000, name: '月销售额' },
              { value: 250000, name: '年销售额' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    };
  },
  mounted() {
    this.initChart();
    this.subscribeData(); // 订阅 SSE 数据
  },
  beforeDestroy() {
    this.cleanup(); // 销毁资源
  },
  methods: {
    /** 初始化图表 */
    initChart() {
      this.chartInstance = echarts.init(this.$refs.pieChart);
      this.chartInstance.setOption(this.option);
    },

    /** 订阅 SSE 数据流 */
    subscribeData() {
      const updateHandler = (data) => {
        if (this.debug) console.log('[SalesPieChart] 收到新数据:', data);
        this.updateChart(data);
      };

      this.unsubscribe = sseManager.subscribe('sales_data', updateHandler);
    },

    /** 更新饼图数据 */
    updateChart(payload) {
      if (!payload || typeof payload !== 'object') {
        console.warn('[SalesPieChart] 数据格式错误:', payload);
        return;
      }

      // 假设后端推送的数据格式为：
      // { day: 800, month: 20000, year: 300000 }

      // 映射后端字段到本地需要的字段名
      const newData = [
        { value: payload['日销售额'] || 0, name: '日销售额' },
        { value: payload['月销售额'] || 0, name: '月销售额' },
        { value: payload['年销售额'] || 0, name: '年销售额' }
      ];

      this.chartInstance.setOption({
        series: [{
          data: newData
        }]
      });
    },

    /** 清理资源 */
    cleanup() {
      if (this.unsubscribe) {
        this.unsubscribe();
      }
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }
    }
  }
};
</script>